#include <pthread.h>
#include <unistd.h>
#include <string.h>

#include <input_manager.h>
#include <page_manager.h>


static PT_EventHandler g_ptEventHandlerHead = NULL;


void EventHandlerRegister(PT_EventHandler ptEventHandler)
{
	ptEventHandler->ptNext = g_ptEventHandlerHead;
	g_ptEventHandlerHead = ptEventHandler;
}


void RemoveHandler(PT_EventHandler handlers){
    PT_EventHandler ptTmp = g_ptEventHandlerHead;
    PT_EventHandler ptPre = ptTmp;

    while (ptTmp){
        if (strcmp(ptTmp->name, handlers->name) == 0){
            ptPre->ptNext = ptTmp->ptNext;
            ptTmp->ptNext = NULL;
            if (ptTmp == g_ptEventHandlerHead)
                g_ptEventHandlerHead = ptTmp->ptNext;
            break;
        }
        ptPre = ptTmp;
        ptTmp = ptTmp->ptNext;
    }
}


void *thread_fuc(void *p){
    int error;
	InputEvent tInputEvent;
    PT_EventHandler ptTmp;
    PT_EventHandler aRemoveHandlers[100];
    unsigned int count = 0;

    while(1){
        error = GetInputEvent(&tInputEvent);
        if (error)
            continue;

        ptTmp = g_ptEventHandlerHead;
        while (ptTmp){
            if (!strcmp(ptTmp->name, GetCurPage()->name)){
                if (ptTmp->HandleFunc){
                    ptTmp->HandleFunc(&tInputEvent);
                }
            }
            else {
                aRemoveHandlers[count++] = ptTmp;
            }
            ptTmp = ptTmp->ptNext;
        }

        for (int j=0; j<count; j++){
            RemoveHandler(aRemoveHandlers[j]);
        }
        count = 0;
    }
}


void EventHandlerInit(void){
    pthread_t tid;
    pthread_create(&tid, NULL, thread_fuc, NULL);
}